package com.xuelangyun.form.exterauth.service.impl;

import java.util.Date;

import com.xuelangyun.form.common.utils.TokenGenerator;
import com.xuelangyun.form.exterauth.dao.ISysExterAppTokenDao;
import com.xuelangyun.form.exterauth.entity.SysExterAppTokenApiEntity;
import com.xuelangyun.form.exterauth.service.ISysExterAppTokenService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


@Service("sysExterAppTokenService")
public class SysExterAppTokenApiServiceImpl extends ServiceImpl<ISysExterAppTokenDao, SysExterAppTokenApiEntity> implements ISysExterAppTokenService {

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;


    @Override
    public SysExterAppTokenApiEntity queryByToken(String token) {
        QueryWrapper<SysExterAppTokenApiEntity> query = new QueryWrapper<>();
        query.eq("token", token);
        return getOne(query);
    }


    public SysExterAppTokenApiEntity queryByAppAndType(String appId, String type) {
        QueryWrapper<SysExterAppTokenApiEntity> query = new QueryWrapper<>();
        query.eq("app_id", appId);
        query.eq("type", type != null && type.equals("pc") ? 1 : 0);
        return getOne(query);
    }


    @Override
    public SysExterAppTokenApiEntity generateToken(String appId, String type) {

        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        SysExterAppTokenApiEntity tokenEntity = queryByAppAndType(appId, type);
        if (tokenEntity == null) {
            tokenEntity = new SysExterAppTokenApiEntity();
            tokenEntity.setAppId(appId);
            tokenEntity.setToken(token);
            tokenEntity.setCreateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            this.save(tokenEntity);
        } else {
            tokenEntity.setToken(token);
            tokenEntity.setCreateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            this.updateById(tokenEntity);
        }
        return tokenEntity;
    }

}
